//
//  SRAlarm+Cate.m
//  SportRing
//
//  Created by Apple on 14/10/27.
//  Copyright (c) 2014年 HotOne. All rights reserved.
//

#import "SRAlarm+Cate.h"
#import "SRMe+Cate.h"

@implementation SRAlarm (Cate)

+ (SRAlarm *)alarmWithId:(NSInteger)alarmId
{
    __block SRAlarm * alarm = nil;
    [MagicalRecord saveUsingCurrentThreadContextWithBlockAndWait:^(NSManagedObjectContext *localContext)
     {
         alarm = [SRAlarm MR_createEntity];
         alarm.alarmId = @(alarmId);
     }];
    return alarm;
}

- (void)configAttributesWithBlock:(void(^)(SRAlarm * aSelf))block
{
    [MagicalRecord saveUsingCurrentThreadContextWithBlockAndWait:^(NSManagedObjectContext *localContext)
     {
         block(self);
         
     }];
}

@end


@implementation SRAlarm (Find)

+ (SRAlarm *)findAlarmForMe:(SRMe *)me alarmId:(NSInteger)alarmId
{
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"alarmId == %d AND me.userName == %@",
                               alarmId, me.userName];
    return [SRAlarm MR_findFirstWithPredicate:predicate];
}

+ (SRAlarm *)findAlarmCINEForMe:(SRMe *)me alarmId:(NSInteger)alarmId
{
    SRAlarm * alarm = [SRAlarm findAlarmForMe:me alarmId:alarmId];
    if (alarm == nil) {
        alarm = [SRAlarm alarmWithId:alarmId];
        [alarm configAttributesWithBlock:^(SRAlarm *aSelf) {
            aSelf.me = me;
        }];
    }
    return alarm;
}

+ (NSArray *)findAlarmForMe:(SRMe *)me
{
    return [[me.alarms allObjects] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        SRAlarm * alarm1 = obj1;
        SRAlarm * alarm2 = obj2;
        return [alarm1.alarmId compare:alarm2.alarmId];
    }];
}

@end